<?php
/**
 * MsgController is an instance of Controller (application.components). 
 *
 * Controller is an instance of CController (system.web).
 * CController manages a set of actions which deal with the corresponding user requests. 
 * Through the actions, CController coordinates the data flow between models and views. 
 *
 * Eduow :  International system for education (http://eduow.com)
 * Copyright 2010, Nikolay Stoitsev 
 *
 * Licensed under GNU General Public License version 2
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @copyright     Copyright 2010
 * @link          http://eduow.com Eduow Project
 * @package       eduow
 * @subpackage    application.controllers
 * @inheritance   class MsgController » Controller » CController » CBaseController » CComponent
 * @implements    
 * @since         Eduow v 0.0.3
 * @license       http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License version 2
 */

class MsgController extends Controller
{
    /**
     * @var string specifies the default action to be 'list'.
     */
    public $defaultAction='list';

    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_msg;

    /**
     * Declares class-based actions.
     */
    public function actions()
    {
        return array(
            // captcha action renderPartials the CAPTCHA image
            // this is used by the contact page
            'captcha'=>array(
                'class'=>'CCaptchaAction',
                'backColor'=>0xF5F5F5,
            ),
        );
    }

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            '*' => array(Group::USER, 'min'),
        );
    }

    /**
     * Creates a new message.
     * If creation is successful, the browser will display a message.
     */
    public function actionSend()
    {
        $msg=new Msg;

        if(isset($_POST['Msg']))
        {
            $msg->attributes=$_POST['Msg'];
            $criteria=new CDbCriteria;
            $criteria->condition='username=:id';
            $criteria->params=array(':id'=>$msg->name);
            $msg->from=Yii::app()->user->id;
	    if($user = User::model()->find($criteria)){
            	$msg->to = $user->id;
	    }else{
		$msg->addError('name','Потребителя не съществува');
	    }
            if($msg->validate()){

                $msg->save();

		Yii::app()->user->setFlash('model', Yii::t('yii','Your message have been sended succesfully.'));
            }
        }else{
            $msg->to = $_GET['to'];
            if($_GET['subject']){
                $msg->subject = 'Отговор:'.$_GET['subject'];
            }
        }

        $this->render('send',array('msg'=>$msg));
    }



    /**
     * Deletes a particular message.
     * If deletion is successful, the browser will display a message.
     */
    public function actionDelete()
    {
        if(Yii::app()->request->isPostRequest)
        {
            // we only allow deletion via POST request
            $this->loadPost()->delete();
            $this->redirect(array('list'));
        }
        else
        throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all messages.
     */
    public function actionList()
    {
        $new = Msg::model()->findAllByAttributes(array('read'=>0,'to'=>Yii::app()->user->id));
        $received = Msg::model()->findAllByAttributes(array('to'=>Yii::app()->user->id));
        $sended = Msg::model()->findAllByAttributes(array('from'=>Yii::app()->user->id));

        $this->render('list',array(
            'sended'=>$sended,
            'received'=>$received,
                    'new'=>$new,
            ));
    }




    /**
     * Read function renders paricular
     * message which user wants to view
     */
    public function actionRead(){
        $msg=$this->loadMsg();

        if($msg->to==Yii::app()->user->id){
            Msg::model()->updateByPk($msg->id, array('read'=>'1'));
        }

        $this->render('view',array(
            'msg'=>$msg
            ));

    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
     */
    protected function loadMsg($id=null)
    {
        if($this->_msg===null)
        {
            if($id!==null || isset($_GET['id']))
            $this->_msg=Msg::model()->findbyPk($id!==null ? $id : $_GET['id']);
            if($this->_msg===null || Yii::app()->user->isGuest && md5($this->_msg->subject)!=md5($_GET['sid']))
            throw new CHttpException(404,'Няма намерено съобщение.');
        }
        return $this->_msg;
    }


}
?>
